﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;
using System.IO;
using System.Xml;

namespace FeedNet
{
    public class Feeder
    {

        private IWebReader _reader;

        public Feeder()
        {
            _reader = new SimpleWebReader();
        }

        public Feeder(IWebReader webReader)
        {
            _reader = webReader;
        }

        /*
         * Feed getFeed(string uri) 
         * parse a single feed and return the resulting feed object
         * 
         */
        public Feed getFeed(string uri)
        {
            Stream rss_stream = _reader.getWebStream(uri);
      
            Feed f = getFeedFromStream(rss_stream);
            f.feed_url = uri;
            return f;
        }

        /*
         * Feed updateFeed(Feed x)
         * get the latest entries for this feed
         * 
         */
        public Feed updateFeed(Feed f)
        {
            Feed updated_feed = new Feed();
            updated_feed = getFeed(f.feed_url);

            updated_feed.new_entries.Clear();

            DateTime latest_old = f.entries.First().date_published;
            foreach (Entry newEntry in updated_feed.entries)
            {
                if (DateTime.Compare(newEntry.date_published, latest_old) > 0)
                {
                    updated_feed.new_entries.Add(newEntry);
                }
            }
            return updated_feed;
        }

        /*
         * Feed getFeedFromStream
         * given a stream parse the feed using XmlTextReader
         */ 
        public Feed getFeedFromStream(Stream s)
        {
            Feed f = new Feed();
            f.loadFromStream(s);           
            return f;
        }

       

    }
}
